package ynu.edu.achitectureclass.service.AirSensorService;

import ynu.edu.achitectureclass.entity.Air_temp;
import ynu.edu.achitectureclass.entity.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ynu.edu.achitectureclass.repository.Air_temp_Repository;
import ynu.edu.achitectureclass.service.BaseSensorService;
import ynu.edu.achitectureclass.service.SensorService;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class Air_temp_Service extends BaseSensorService<Air_temp> implements SensorService<Air_temp> {

    @Autowired
    private Air_temp_Repository air_temp_Repository;

    @Override
    protected void storeSoilData(Object data) {
        if (data instanceof List) {
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) data;
            for (Map<String, Object> dataMap : dataList) {
                String sensorSerialNumber = (String) dataMap.get("id");
                String name = (String) dataMap.get("name");
                Object valueObj = dataMap.get("value");
                Double value = null;

                if (valueObj instanceof Integer) {
                    value = ((Integer) valueObj).doubleValue() / 10;
                } else if (valueObj instanceof Double) {
                    value = (Double) valueObj / 10;
                } else {
                    throw new IllegalArgumentException("Unexpected type for value: " + valueObj.getClass());
                }

                String timestamp = (String) dataMap.get("timestamp");

                Optional<Device> deviceOpt = deviceRepository.findBySerialNumber(sensorSerialNumber);
                if (!deviceOpt.isPresent()) {
                    throw new IllegalArgumentException("Device with serial number " + sensorSerialNumber + " not found");
                }
                Device device = deviceOpt.get();

                Air_temp airTemp = new Air_temp();
                airTemp.setDeviceId(device.getId());
                airTemp.setName(name);
                airTemp.setValue(value);
                LocalDateTime createdAt = LocalDateTime.parse(timestamp.replace("Z", ""));
                airTemp.setCreatedAt(createdAt);

                air_temp_Repository.save(airTemp);
            }
        } else {
            throw new IllegalArgumentException("Invalid data format.");
        }
    }

    @Override
    public Air_temp getLatestData() {
        return (Air_temp) air_temp_Repository.findTopByOrderByCreatedAtDesc()
                .orElseThrow(() -> new IllegalArgumentException("No air temperature data found."));
    }

    @Override
    public List<Air_temp> getAllData() {
        return air_temp_Repository.findAll();
    }
}